package com.halloon.android.ui.fragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.halloon.android.R;
import com.halloon.android.adapter.TweetContentAdapter;
import com.halloon.android.bean.ProfileBean;
import com.halloon.android.bean.TweetBean;
import com.halloon.android.data.ContentManager;
import com.halloon.android.data.DBManager;
import com.halloon.android.data.SettingsManager;
import com.halloon.android.task.LocationTask;
import com.halloon.android.util.Constants;
import com.halloon.android.util.PopupWindowManager;
import com.halloon.android.util.TimeUtil;
import com.halloon.android.view.PullToRefreshListView;
import com.halloon.android.view.PullToRefreshListView.OnRefreshListener;

public class TabMainPageFragment extends SherlockFragment implements OnClickListener{
	
	private MainPageFragmentCallback mpCallback;
	private PullToRefreshListView pullToRefreshListView;
	private Button sendButton;
	private Button aroundButton;
	private Button backButton;
	private Button fanButton;
    private RelativeLayout lineContainer;
	private Context context;
	private TextView titleText;
	ArrayList<TweetBean> tweetContainer;
	TweetContentAdapter tweetContentAdapter;
	
	public static final int MAIN_TIMELINE_TWEET = 1;
	public static final int OTHER_TWEET = 2;
	public static final int AROUND_TWEET = 3;
	
	private int tweetState = MAIN_TIMELINE_TWEET;
	private String otherName;
	private String myName;
	private String nick;
	
	private String longitude;
	private String latitude;
	
	private AsyncTask<Void, Void, String> task;
	private LocationTask locationTask;
	private MyBroadCastReceiver mBroadCast = null;
	private DelBroadCastReceiver delBroadCast = null;

    private float eventY;
	
	public interface MainPageFragmentCallback{
		
		public void setupDetailFragment(Bundle bundle);
		public void setupPublishFragment();
		public void setupCommentFragment(Bundle bundle);
		public void setupAroundTweetFragment();
		public void destroyMainPageFragment();
		public void setupPictureDialog(String addr, String preSize);
		
	}
	
	@Override
	public void onAttach(Activity activity){
		super.onAttach(activity);
		this.mpCallback = (MainPageFragmentCallback) activity;
		context = activity;
		
		if(getArguments().getString("name") != null) otherName = getArguments().getString("name");
		if(getArguments().getString("nick") != null) nick = getArguments().getString("nick");
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.tab_mainpage, null, false);
	    
		pullToRefreshListView = (PullToRefreshListView) root.findViewById(R.id.list);
		
		titleText = (TextView) root.findViewById(R.id.title_text);
		sendButton = (Button) root.findViewById(R.id.send_button);
		aroundButton = (Button) root.findViewById(R.id.around_button);
		backButton = (Button) root.findViewById(R.id.back_button);
		fanButton = (Button) root.findViewById(R.id.fan_button);
		lineContainer = (RelativeLayout) root.findViewById(R.id.line_container);
		
		tweetContainer = new ArrayList<TweetBean>();
		tweetContentAdapter = new TweetContentAdapter(context,tweetContainer);
		pullToRefreshListView.setAdapter(tweetContentAdapter);
		sendButton.setOnClickListener(this);
		aroundButton.setOnClickListener(this);
		backButton.setOnClickListener(this);
		fanButton.setOnClickListener(this);
		titleText.setClickable(true);
		titleText.setOnClickListener(this);
		
		loadData();
		
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		if(DBManager.getInstance(context).getProfile().getName() == null){
			new Thread(){
				@Override
				public void run(){
					ProfileBean profileBean = ContentManager.getInstance(context).getMyProfile();
					DBManager.getInstance(context).upgradeProfile(profileBean);
					myName = profileBean.getName();
				}
			}.start();
		}else{
			myName = DBManager.getInstance(context).getProfile().getName();
		}
		
		//customize fastscroll bar style
		try{
			Field f = AbsListView.class.getDeclaredField("mFastScroller");
			f.setAccessible(true);
			Object o = f.get(pullToRefreshListView);
			f = f.getType().getDeclaredField("mThumbDrawable");
			f.setAccessible(true);
			Drawable drawable = (Drawable) f.get(o);
			drawable = context.getResources().getDrawable(R.drawable.ic_launcher);
			f.set(o, drawable);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		pullToRefreshListView.setOnRefreshListener(new OnRefreshListener() {
			public void onRefresh() {refreshData();}
		});
		pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Bundle bundle = new Bundle();
				bundle.putString("id", tweetContentAdapter.getItem(position - 1).getId());
			    mpCallback.setupDetailFragment(bundle);
			}
			
		});
		pullToRefreshListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				PopupWindowManager popupWindowManager = new PopupWindowManager(context);
				if(otherName != null && otherName.equals(myName)){
					popupWindowManager.setupCommentFunctionPopup(tweetContentAdapter.getItem(position - 1).getId(), tweetContentAdapter.getItem(position - 1).getName().equals(myName), tweetContentAdapter.getItem(position - 1).getText(), PopupWindowManager.MY_TWEET_FUNCTION, position - 1);
				}else if(otherName == null && tweetState == OTHER_TWEET){
					popupWindowManager.setupCommentFunctionPopup(tweetContentAdapter.getItem(position - 1).getId(), tweetContentAdapter.getItem(position - 1).getName().equals(myName), tweetContentAdapter.getItem(position - 1).getText(), PopupWindowManager.MY_TWEET_FUNCTION, position - 1);
				}else{
					popupWindowManager.setupCommentFunctionPopup(tweetContentAdapter.getItem(position - 1).getId(), tweetContentAdapter.getItem(position - 1).getName().equals(myName), tweetContentAdapter.getItem(position - 1).getText(), PopupWindowManager.OTHER_TWEET_FUNCTION, position - 1);
				}
				return true;
			}
			
		});
		
		pullToRefreshListView.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				eventY = event.getRawY();
				return false;
			}
			
		});
		
		switch(tweetState){
		case MAIN_TIMELINE_TWEET:
			backButton.setVisibility(View.GONE);
			fanButton.setVisibility(View.GONE);
			sendButton.setVisibility(View.VISIBLE);
			aroundButton.setVisibility(View.VISIBLE);
			lineContainer.setVisibility(View.VISIBLE);
			String tmp_nick = DBManager.getInstance(context).getProfile().getNick();
			if(SettingsManager.getInstance(context).getProfileStatus() == DBManager.PROFILE_STATUS_READY && (tmp_nick != null || !tmp_nick.equals(""))){
			    titleText.setText(tmp_nick);
		    }else{
			    new Thread(){
			    	@Override
			    	public void run(){
			    		ProfileBean profileBean = ContentManager.getInstance(context).getMyProfile();
			    		titleText.setText(profileBean.getNick());
			    		DBManager.getInstance(context).upgradeProfile(profileBean);
			    	}
			    }.start();
		    }
		    break;
		case OTHER_TWEET:
			backButton.setVisibility(View.VISIBLE);
			sendButton.setVisibility(View.GONE);
			aroundButton.setVisibility(View.GONE);
			fanButton.setVisibility(View.VISIBLE);
			lineContainer.setVisibility(View.GONE);
			titleText.setText(nick);
			break;
		case AROUND_TWEET:
			backButton.setVisibility(View.VISIBLE);
			sendButton.setVisibility(View.GONE);
			aroundButton.setVisibility(View.GONE);
			fanButton.setVisibility(View.GONE);
			lineContainer.setVisibility(View.GONE);
			titleText.setText(context.getString(R.string.nearby_tweet));
			break;
		default:
			if(SettingsManager.getInstance(context).getProfileStatus() == DBManager.PROFILE_STATUS_READY){
				titleText.setText(DBManager.getInstance(context).getProfile().getNick());
			}else{
				titleText.setText(ContentManager.getInstance(context).getMyProfile().getNick());
			}
			break;
		}
	}
	
	@Override
	public void onStart(){
		super.onStart();
		if(tweetState == AROUND_TWEET){
			mBroadCast = new MyBroadCastReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(Constants.LOCATION_GOT_LOCATION);
			
			context.registerReceiver(mBroadCast, filter);
		}
		delBroadCast = new DelBroadCastReceiver();
		IntentFilter delFilter = new IntentFilter();
		delFilter.addAction(Constants.DEL_CONFIRM);
		
		context.registerReceiver(delBroadCast, delFilter);	
	}
	

	private void loadData(){
		
		task = new AsyncTask<Void, Void, String>(){
			
			@Override
			protected String doInBackground(Void... arg0){
					ArrayList<TweetBean> tmpArrayList = new ArrayList<TweetBean>();
					
					tweetContainer.clear();
					
					switch(tweetState){
					case MAIN_TIMELINE_TWEET:
						if(SettingsManager.getInstance(context).getTweetListStatus() == DBManager.TWEET_LIST_STATUS_INIT){
							tmpArrayList = ContentManager.getInstance(context).getHomeTimeLineTweet("", "", 40, "", "");
							
							HashMap<String, TweetBean> tweetLists = new HashMap<String, TweetBean>();
							for(int i=0; i<tmpArrayList.size(); i++) {
								tweetLists.put(tmpArrayList.get(i).getTimestamp(), (TweetBean) tmpArrayList.get(i));
							}
							
							DBManager.getInstance(context).addTweetListContent(tweetLists, true);

							SettingsManager.getInstance(context).setLastUpdateTime(context.getString(R.string.refresh_at) + TimeUtil.getCurrentTime());
							
							tweetContainer.addAll(tmpArrayList);
						}else{
							tweetContainer.addAll(DBManager.getInstance(context).getAllTweetList());
						}
						break;
					case OTHER_TWEET:
						tmpArrayList = ContentManager.getInstance(context).getOtherTimeLine("", "", 40, "", otherName, null, "", "");
						
						tweetContainer.addAll(tmpArrayList);
						break;
					}
					
				return null;
			}
			
			@Override
			protected void onPostExecute(String result){
				tweetContentAdapter.notifyDataSetChanged();
				pullToRefreshListView.onRefreshComplete();
				super.onPostExecute(result);
			}
		};
		
        locationTask = new LocationTask(context);
		
		if(tweetState != AROUND_TWEET){
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
	  			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	  		} else {
	  			task.execute();
	  		}
		}else{
			if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
				locationTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}else{
				locationTask.execute();
			}
			pullToRefreshListView.onRefresh();
		}
	}
	
	public void refreshData(){
		task = new AsyncTask<Void, Void, String>(){

			@Override
			protected String doInBackground(Void... params) {
				ArrayList<TweetBean> tmpArrayList = new ArrayList<TweetBean>();
				
				switch(tweetState){
				case MAIN_TIMELINE_TWEET:
					tmpArrayList = ContentManager.getInstance(context).getHomeTimeLineTweet("", "", 40, "", "");
					
					if(tmpArrayList.size() != 0){
						HashMap<String, TweetBean> tweetLists = new HashMap<String, TweetBean>();
						for(int i=0; i<tmpArrayList.size(); i++) {
							tweetLists.put(tmpArrayList.get(i).getTimestamp(), tmpArrayList.get(i));
						}
						
						DBManager.getInstance(context).addTweetListContent(tweetLists, true);
						tweetContainer.clear();
						tweetContainer.addAll(tmpArrayList);
						
						SettingsManager.getInstance(context).setLastUpdateTime(context.getString(R.string.refresh_at) + TimeUtil.getCurrentTime());
						
						return "success";
					}else{
						return "failure";
					}
				case OTHER_TWEET:
					tmpArrayList = ContentManager.getInstance(context).getOtherTimeLine("", "", 40, "", otherName, null, "", "");
					
					tweetContainer.clear();
					tweetContainer.addAll(tmpArrayList);
					break;
				}
				return "success";
				
			}
			
			@Override
			protected void onPostExecute(String result){
				if(result.equals("success")){
					tweetContentAdapter.notifyDataSetChanged();
				}else{
					Toast.makeText(context, context.getString(R.string.refresh_failure), Toast.LENGTH_LONG).show();
				}
				pullToRefreshListView.onRefreshComplete();
			}
			
		};
		
		locationTask = new LocationTask(context);
		
		if(tweetState != AROUND_TWEET){
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
	  			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	  		} else {
	  			task.execute();
	  		}
		}else{
			if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
				locationTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}else{
				locationTask.execute();
			}
		}
		
	}
	
	private void loadAroundTweet(){
		AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>(){
			@Override
			protected String doInBackground(Void... params){
				ArrayList<TweetBean> tmp_list = ContentManager.getInstance(context).getAroundTweet(longitude, latitude, "0", "25");
				
				tweetContainer.clear();
				tweetContainer.addAll(tmp_list);
				return null;
			}
			
			@Override
			protected void onPostExecute(String result){
				tweetContentAdapter.notifyDataSetChanged();
				pullToRefreshListView.onRefreshComplete();
			}
		};
		
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			task.execute();
		}
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.send_button:
			mpCallback.setupPublishFragment();
		    break;
		case R.id.around_button:
			mpCallback.setupAroundTweetFragment();
		    break;
		case R.id.back_button:
			mpCallback.destroyMainPageFragment();
		    break;
		case R.id.fan_button:
			break;
		case R.id.title_text:
			if(tweetState == MAIN_TIMELINE_TWEET){
				PopupWindowManager pwManager = new PopupWindowManager(context);
				ArrayList<String> arrayList = new ArrayList<String>();
				arrayList.add("your group");
				arrayList.add("my group");
				arrayList.add("his group");
				arrayList.add("her group");
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrayList);
				pwManager.setupTitleListPopup(R.id.title_text, adapter);
			}
		}
	}
	
	public void setTweetState(int tweetState){
		this.tweetState = tweetState;
	}
	
	@Override
	public void onStop(){
		super.onStop();
		if(task.getStatus() == AsyncTask.Status.RUNNING) task.cancel(true);
		if(locationTask != null)locationTask.cancel(true); 
		if(tweetState == AROUND_TWEET){
			context.unregisterReceiver(mBroadCast);
		}
		
		context.unregisterReceiver(delBroadCast);
	}
	
	private class MyBroadCastReceiver extends BroadcastReceiver{
		
		@Override
		public void onReceive(Context context, Intent intent){
			Bundle bundle = intent.getExtras();
			longitude = String.valueOf(bundle.getDouble("longitude"));
			latitude = String.valueOf(bundle.getDouble("latitude"));
			
			loadAroundTweet();
		}

	}
	
	private class DelBroadCastReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent){
			Bundle bundle = intent.getExtras();
			tweetContentAdapter.removeItem(bundle.getInt("position"));
		}
	}
}
	
